package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.datapush.service.apipush.utils.XinDaiMaskUtil;
import com.block.datapush.service.apipush.utils.XinDaiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.block.db.mapper.MerchantBaseInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 安易融  双授权
 */
@Service
public class XinDaiApiSMaskPushService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    MerchantBaseInfoMapper merchantBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:0);
        paramMap.put("nameMd5", getMD5(memberSourceInfo.getRealname()));
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("idCardMd5",getMD5(memberSourceInfo.getIdcard()));
        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        paramMap.put("city",city);
        paramMap.put("socialSecurity", XinDaiMaskUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiMaskUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiMaskUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiMaskUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiMaskUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiMaskUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiMaskUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiMaskUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiMaskUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiMaskUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiMaskUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());
        paramMap.put("huaBeiQuota", XinDaiMaskUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baiTiaoQuota", XinDaiMaskUtil.getJd(memberSourceInfo.getBaitiao()));

        String iv = XinDaiUtil.getIV();
        String encrypt = XinDaiUtil.encryptCbc(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(),iv);
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("iv",iv);
        aceMap.put("data",encrypt);

        log.info("【信贷全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{} ", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷全流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        JSONArray jsonObject1 = resultObject.getJSONArray("data");
        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        String companyLogo =merchantBaseInfoMapper.getInfoLogoById(pushApiKeyParam.getInfoId());
        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = jsonObject1.getJSONObject(0);
            JSONArray hitPhoneList = data.getJSONArray("hitPhoneList");
                if (MobileMd5IsInListUtils.isMobileMd5InList(hitPhoneList, mobileMd5)) {
                    // 存在
                    pushApiResult.setCode(code + "|" + "500");
                    pushApiResult.setMessage(msg + "|" + mobileMd5 + "号码已存在");
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
            Boolean check = data.getBoolean("check");
            if(check){
                    String productName = data.getString("productName");
                    String loanName = data.getString("loanName");
                    String serialNo = data.getString("serialNo");
                    extJson.put("serialNo", serialNo);
                    //进行分润操作
                    String priceType = pushApiKeyParam.getPriceType();
                    BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                    if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                        BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                        if (price.compareTo(new BigDecimal(0.00)) == -1){
                            pushApiResult.setPushSuccess(false);
                            return pushApiResult;
                        }
                        BigDecimal priceLeft = price.divide(typeRate,2, RoundingMode.HALF_UP);//分润前价格
                        pushApiResult.setPrice(priceLeft);
                        pushApiResult.setPriceRight(price);
                    }

                    // 撞库成功之后，商户的机构数据存储
                    thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                    thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                    thirdInfoDTO.setOrderNo(orderNo);
                    JSONObject infoObject = new JSONObject();
                    infoObject.put("orderNo",serialNo);
                    infoObject.put("companyLogo",companyLogo);
                    infoObject.put("productId",serialNo);
                    infoObject.put("productName",productName);
                    infoObject.put("companyName",loanName);
                    infoObject.put("maxLoanAmount","200000");
                    infoObject.put("maxLoanRate","20");
                    infoObject.put("minLoanRate","1");
                    infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
                    JSONArray jsonArray = new JSONArray();
                    JSONArray agreementList = data.getJSONArray("authorizationAgreement");
                    for (int i=0;i<agreementList.size();i++){
                        JSONObject jsonObject = new JSONObject();
                        String agreemenName = agreementList.getJSONObject(i).getString("name");
                        String agreemenUrl = agreementList.getJSONObject(i).getString("url");
                        jsonObject.put("protocalName",agreemenName);
                        jsonObject.put("protocalUrl",agreemenUrl);
                        jsonArray.add(jsonObject);
                    }
                    infoObject.put("agreements",jsonArray);
                    thirdInfoDTO.setInfoObject(infoObject);
                }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);

            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    private Object getMD5(String realName) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(realName.getBytes());
            byte[] digest = md.digest();
            BigInteger no = new BigInteger(1, digest);
            String  nameMd5 = no.toString(16);
            return nameMd5;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        String serialNo = extJson.getString("serialNo");
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?1:0);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("idCard",memberSourceInfo.getIdcard());
        paramMap.put("city",memberSourceInfo.getCity().substring(0,memberSourceInfo.getCity().length()-1));
        paramMap.put("socialSecurity", XinDaiMaskUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiMaskUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiMaskUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiMaskUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiMaskUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiMaskUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiMaskUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiMaskUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiMaskUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiMaskUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiMaskUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());
        paramMap.put("huaBeiQuota", XinDaiMaskUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baiTiaoQuota", XinDaiMaskUtil.getJd(memberSourceInfo.getBaitiao()));


        String iv = XinDaiUtil.getIV();
        String encrypt = XinDaiUtil.encryptCbc(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(),iv);
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("iv",iv);
        aceMap.put("serialNo",serialNo);
        aceMap.put("data",encrypt);

        log.info("【信贷全流程】导单开始【queryUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷全流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobileMask());
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:0);
        paramMap.put("nameMd5", getMD5(memberSourceInfo.getRealname()));
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("idCardMd5",getMD5(memberSourceInfo.getIdcard()));
        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        paramMap.put("city",city);
        paramMap.put("socialSecurity", XinDaiMaskUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiMaskUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiMaskUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiMaskUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiMaskUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiMaskUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiMaskUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiMaskUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiMaskUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiMaskUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiMaskUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());
        paramMap.put("huaBeiQuota", XinDaiMaskUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baiTiaoQuota", XinDaiMaskUtil.getJd(memberSourceInfo.getBaitiao()));

        String iv = XinDaiUtil.getIV();
        String encrypt = XinDaiUtil.encryptCbc(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(),iv);
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("iv",iv);
        aceMap.put("data",encrypt);

        log.info("【上游信贷全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{} ", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【上游信贷全流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        JSONArray jsonObject1 = resultObject.getJSONArray("data");
        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        String companyLogo =merchantBaseInfoMapper.getInfoLogoById(pushApiKeyParam.getInfoId());
        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = jsonObject1.getJSONObject(0);
            JSONArray hitPhoneList = data.getJSONArray("hitPhoneList");
            pushApiResult.setMd5List(hitPhoneList);
            Boolean check = data.getBoolean("check");
            if(check){
                String productName = data.getString("productName");
                String loanName = data.getString("loanName");
                String serialNo = data.getString("serialNo");
                extJson.put("serialNo", serialNo);
                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                    if (price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceLeft = price.divide(typeRate,2, RoundingMode.HALF_UP);//分润前价格
                    pushApiResult.setPrice(priceLeft);
                    pushApiResult.setPriceRight(price);
                }

                // 撞库成功之后，商户的机构数据存储
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo",serialNo);
                infoObject.put("companyLogo",companyLogo);
                infoObject.put("productId",serialNo);
                infoObject.put("productName",productName);
                infoObject.put("companyName",loanName);
                infoObject.put("maxLoanAmount","200000");
                infoObject.put("maxLoanRate","20");
                infoObject.put("minLoanRate","1");
                infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                JSONArray agreementList = data.getJSONArray("authorizationAgreement");
                for (int i=0;i<agreementList.size();i++){
                    JSONObject jsonObject = new JSONObject();
                    String agreemenName = agreementList.getJSONObject(i).getString("name");
                    String agreemenUrl = agreementList.getJSONObject(i).getString("url");
                    jsonObject.put("protocalName",agreemenName);
                    jsonObject.put("protocalUrl",agreemenUrl);
                    jsonArray.add(jsonObject);
                }
                infoObject.put("agreements",jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);

            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }
}
